package com.sx.zongzhi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sx.zongzhi.BaseActivity;
import com.sx.zongzhi.R;
import com.sx.zongzhi.adapter.SpinnerPubAdapter;
import com.sx.zongzhi.bean.GlobalBean;
import com.sx.zongzhi.bean.MsgEvent;
import com.sx.zongzhi.bean.PhotoBean;
import com.sx.zongzhi.bean.PublicBean;
import com.sx.zongzhi.presenter.AddEconomicOrganizationPest;
import com.sx.zongzhi.presenter.PublicListPest;
import com.sx.zongzhi.presenter.UploadFilePest;
import com.sx.zongzhi.utils.BaseUtil;
import com.sx.zongzhi.utils.MyRxBus;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.CommentView;
import com.sx.zongzhi.view.IPublicBeanView;
import com.sx.zongzhi.view.UploadFileView;
import com.sx.zongzhi.widget.LoadDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 添加非公有制经济组织
 * Created by admin on 2017/12/8.
 */

public class AddEconomicOrganizationActivity extends BaseActivity implements CommentView, IPublicBeanView, UploadFileView {
    @BindView(R.id.imv_Head)
    ImageView imvHead;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_residence)
    EditText etResidence;
    @BindView(R.id.et_enterpriseMobile)
    EditText etEnterpriseMobile;
    @BindView(R.id.et_enterpriseTelephone)
    EditText etEnterpriseTelephone;
    @BindView(R.id.rg_isDangerousEnterprise)
    RadioGroup rgIsDangerousEnterprise;
    @BindView(R.id.et_cardNo)
    EditText etCardNo;
    @BindView(R.id.et_chief)
    EditText etChief;
    @BindView(R.id.et_mobileNumber)
    EditText etMobileNumber;
    @BindView(R.id.et_telephone)
    EditText etTelephone;
    @BindView(R.id.et_chiefSafe)
    EditText etChiefSafe;
    @BindView(R.id.et_mobileNumberSafe)
    EditText etMobileNumberSafe;
    @BindView(R.id.et_telephoneSafe)
    EditText etTelephoneSafe;
    @BindView(R.id.et_licenseNumber)
    EditText etLicenseNumber;
    @BindView(R.id.rg_isHaveOrganizationCondition)
    RadioGroup rgIsHaveOrganizationCondition;
    @BindView(R.id.rg_isHaveOrganization)
    RadioGroup rgIsHaveOrganization;
    @BindView(R.id.rg_isHaveGuild)
    RadioGroup rgIsHaveGuild;
    @BindView(R.id.rg_isHaveGroup)
    RadioGroup rgIsHaveGroup;
    @BindView(R.id.rg_isHaveWomenFederation)
    RadioGroup rgIsHaveWomenFederation;
    @BindView(R.id.et_employeeNumber)
    EditText etEmployeeNumber;
    @BindView(R.id.et_partyMemberNumber)
    EditText etPartyMemberNumber;
    @BindView(R.id.et_theMemeberOfGuild)
    EditText etTheMemeberOfGuild;
    @BindView(R.id.et_theMemeberOfWomenFederation)
    EditText etTheMemeberOfWomenFederation;
    @BindView(R.id.et_theMemeberOfGroup)
    EditText etTheMemeberOfGroup;
    @BindView(R.id.sp_style)
    Spinner spStyle;
    @BindView(R.id.sp_chiefCardType)
    Spinner spChiefCardType;
    @BindView(R.id.sp_attentionExtent)
    Spinner spAttentionExtent;
    @BindView(R.id.sp_dangerType)
    Spinner spDangerType;
    @BindView(R.id.ll_isHaveOrganization)
    RelativeLayout llIsHaveOrganization;
    @BindView(R.id.ll_isHaveGuild)
    RelativeLayout llIsHaveGuild;
    @BindView(R.id.ll_isHaveWomenFederation)
    RelativeLayout llIsHaveWomenFederation;
    @BindView(R.id.ll_isHaveGroup)
    RelativeLayout llIsHaveGroup;

    /**
     * 新经济组织类别 证件代码 社会关注程度 安全隐患类型
     */
    private PublicListPest publicListPest;
    private List<GlobalBean> style;
    private List<GlobalBean> chiefCardType;
    private List<GlobalBean> attentionExtent;
    private List<GlobalBean> dangerType;

    private boolean isDangerousEnterprise = true, isHaveOrganizationCondition = true,
            isHaveOrganization = true, isHaveGuild = true, isHaveGroup = true,
            isHaveWomenFederation = true;

    private String orgId, residence, name, styleId, enterpriseMobile,
            enterpriseTelephone, chiefCardTypeId, cardNo, chief, chiefSafe,
            telephone, mobileNumber, mobileNumberSafe, telephoneSafe, licenseNumber,
            employeeNumber, partyMemberNumber, theMemeberOfGuild,
            theMemeberOfWomenFederation, theMemeberOfGroup, attentionExtentId, dangerTypeId, filePath;

    private boolean isCanLoad = true;
    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_add_economic);
        setTitleName("非公有制经济组织新增");
        ButterKnife.bind(this);
        setTitleRight("提交");

        publicListPest = new PublicListPest(this);
        publicListPest.getPublicList("新经济组织类别");
        publicListPest.getPublicList("证件代码");
        publicListPest.getPublicList("社会关注程度");
        publicListPest.getPublicList("安全隐患类型");

        orgId = getIntent().getStringExtra("orgId");

        initRadioBtn();
    }

    private void initRadioBtn() {
        rgIsDangerousEnterprise.setOnCheckedChangeListener(new OnCheckedChangeListeners());
        rgIsHaveOrganizationCondition.setOnCheckedChangeListener(new OnCheckedChangeListeners());
        rgIsHaveOrganization.setOnCheckedChangeListener(new OnCheckedChangeListeners());
        rgIsHaveGuild.setOnCheckedChangeListener(new OnCheckedChangeListeners());
        rgIsHaveGroup.setOnCheckedChangeListener(new OnCheckedChangeListeners());
        rgIsHaveWomenFederation.setOnCheckedChangeListener(new OnCheckedChangeListeners());
    }

    class OnCheckedChangeListeners implements RadioGroup.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            switch (group.getId()) {
                case R.id.rg_isDangerousEnterprise:
                    if (checkedId == R.id.rbt_Yes) {
                        isDangerousEnterprise = true;
                    } else {
                        isDangerousEnterprise = false;
                    }
                    break;
                case R.id.rg_isHaveOrganizationCondition:
                    if (checkedId == R.id.rbt_Yes1) {
                        isHaveOrganizationCondition = true;
                    } else {
                        isHaveOrganizationCondition = false;
                    }
                    break;
                case R.id.rg_isHaveOrganization:
                    if (checkedId == R.id.rbt_Yes2) {
                        isHaveOrganization = true;
                        llIsHaveOrganization.setVisibility(View.VISIBLE);
                        etPartyMemberNumber.setText("1");
                    } else {
                        isHaveOrganization = false;
                        llIsHaveOrganization.setVisibility(View.GONE);
                        etPartyMemberNumber.setText("0");
                    }
                    break;
                case R.id.rg_isHaveGuild:
                    if (checkedId == R.id.rbt_Yes3) {
                        isHaveGuild = true;
                        llIsHaveGuild.setVisibility(View.VISIBLE);
                        etTheMemeberOfGuild.setText("1");
                    } else {
                        isHaveGuild = false;
                        llIsHaveGuild.setVisibility(View.GONE);
                        etTheMemeberOfGuild.setText("0");
                    }
                    break;
                case R.id.rg_isHaveGroup:
                    if (checkedId == R.id.rbt_Yes4) {
                        isHaveGroup = true;
                        llIsHaveGroup.setVisibility(View.VISIBLE);
                        etTheMemeberOfGroup.setText("1");
                    } else {
                        isHaveGroup = false;
                        llIsHaveGroup.setVisibility(View.GONE);
                        etTheMemeberOfGroup.setText("0");
                    }
                    break;
                case R.id.rg_isHaveWomenFederation:
                    if (checkedId == R.id.rbt_Yes5) {
                        isHaveWomenFederation = true;
                        llIsHaveWomenFederation.setVisibility(View.VISIBLE);
                        etTheMemeberOfWomenFederation.setText("1");
                    } else {
                        isHaveWomenFederation = false;
                        llIsHaveWomenFederation.setVisibility(View.GONE);
                        etTheMemeberOfWomenFederation.setText("0");
                    }
                    break;
            }
        }
    }

    @OnClick({R.id.tv_right, R.id.imv_Head})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_right:
                isCanLoad = true;
                subMit();
                if (isCanLoad){
                    LoadDialog.show(AddEconomicOrganizationActivity.this, "提交中...");
                    if (!BaseUtil.isEmpty(filePath)) {
                        List<File> files = new ArrayList<>();
                        files.add(new File(filePath));
                        new UploadFilePest(this).uploadFile(this, files);
                    } else {
                        commitData("");
                    }
                }
                break;
            case R.id.imv_Head:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .maxSelectNum(1)
                        .previewImage(true)// 是否可预览图片
                        .enableCrop(true)
                        .compress(true)
                        .compressGrade(Luban.CUSTOM_GEAR)
                        .compressMaxKB(200)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效 int
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> picUrls = PictureSelector.obtainMultipleResult(data);
                if (!picUrls.isEmpty()) {
                    for (LocalMedia localMedia : picUrls) {
                        filePath = localMedia.getCompressPath();
                        RequestOptions options = new RequestOptions().centerCrop()
                                .placeholder(R.drawable.shape_ff9f9f_12bgd)
                                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                                .error(R.drawable.shape_ff9f9f_12bgd);
                        Glide.with(this)
                                .load(filePath)
                                .apply(options)
                                .into(imvHead);
                    }
                }
            }
        }
    }

    private void subMit() {
        name = etName.getText().toString().trim();
        if (BaseUtil.isEmpty(name)){
            etName.setError("请输入企业名称");
            isCanLoad = false;
            return;
        }
        if (name.length() > 50){
            etName.setError("长度不能大于50个字符");
            isCanLoad = false;
            return;
        }

        styleId = ((GlobalBean) spStyle.getSelectedItem()).getId();
        if (BaseUtil.isEmpty(styleId)) {
            ToastUtils.showToast(AddEconomicOrganizationActivity.this, "请输入企业类别");
            isCanLoad = false;
            return;
        }

        residence = etResidence.getText().toString().trim();
        if (BaseUtil.isEmpty(residence)){
            etResidence.setError("请输入企业地址");
            isCanLoad = false;
            return;
        }
        if (residence.length() > 30){
            etResidence.setError("长度不能大于30个字符");
            isCanLoad = false;
            return;
        }

        enterpriseMobile = etEnterpriseMobile.getText().toString().trim();
        enterpriseTelephone = etEnterpriseTelephone.getText().toString().trim();
        if (BaseUtil.isEmpty(enterpriseMobile) && BaseUtil.isEmpty(enterpriseTelephone)) {
            ToastUtils.showToast(AddEconomicOrganizationActivity.this, "请输入企业联系方式");
            isCanLoad = false;
            return;
        }
        if (!BaseUtil.isMobile(enterpriseMobile)){
            etEnterpriseMobile.setError("请输入正确手机号格式");
            isCanLoad = false;
            return;
        }

        chief = etChief.getText().toString().trim();
        if (BaseUtil.isEmpty(chief)){
            etChief.setError("请输入法定代表人姓名");
            isCanLoad = false;
            return;
        }
        if (chief.length() > 20 || chief.length() < 2) {
            etChief.setError("长度不能小于2个或大于20个字符");
            isCanLoad = false;
            return;
        }

        mobileNumber = etMobileNumber.getText().toString().trim();
        telephone = etTelephone.getText().toString().trim();
        if (BaseUtil.isEmpty(telephone) && BaseUtil.isEmpty(mobileNumber)) {
            ToastUtils.showToast(AddEconomicOrganizationActivity.this, "请法定代表人联系方式");
            isCanLoad = false;
            return;
        }
        if (!BaseUtil.isMobile(mobileNumber)){
            etMobileNumber.setError("请输入正确手机号格式");
            isCanLoad = false;
            return;
        }

        chiefCardTypeId = ((GlobalBean) spChiefCardType.getSelectedItem()).getId();
        if (BaseUtil.isEmpty(chiefCardTypeId)) {
            ToastUtils.showToast(AddEconomicOrganizationActivity.this, "请选择法定代表人证件代码");
            isCanLoad = false;
            return;
        }

        cardNo = etCardNo.getText().toString().trim();
        if (BaseUtil.isEmpty(cardNo)){
            etCardNo.setError("请输入法定代表人证件号码");
            isCanLoad = false;
            return;
        }
        if (cardNo.length() > 50) {
            etCardNo.setError("长度不能大于50个字符");
            isCanLoad = false;
            return;
        }

        chiefSafe = etChiefSafe.getText().toString().trim();
        if (BaseUtil.isEmpty(chiefSafe)){
            etChiefSafe.setError("请输入治保负责人姓名");
            isCanLoad = false;
            return;
        }
        if (chiefSafe.length() > 20 || chiefSafe.length() < 2) {
            etChiefSafe.setError("长度不能小于2个或大于20个字符");
            isCanLoad = false;
            return;
        }

        mobileNumberSafe = etMobileNumberSafe.getText().toString().trim();
        telephoneSafe = etTelephoneSafe.getText().toString().trim();
        if (BaseUtil.isEmpty(mobileNumberSafe) && BaseUtil.isEmpty(telephoneSafe)) {
            ToastUtils.showToast(AddEconomicOrganizationActivity.this, "请输入治保负责人联系方式");
            isCanLoad = false;
            return;
        }
        if (!BaseUtil.isMobile(mobileNumberSafe)){
            etMobileNumberSafe.setError("请输入正确手机号格式");
            isCanLoad = false;
            return;
        }

        licenseNumber = etLicenseNumber.getText().toString().trim();
        if (BaseUtil.isEmpty(licenseNumber)){
            etChiefSafe.setError("请输入工商执照注册号(统一社会信用代码)");
            isCanLoad = false;
            return;
        }
        if (licenseNumber.length() > 18) {
            etChiefSafe.setError("长度不能大于18个字符");
            isCanLoad = false;
            return;
        }

        employeeNumber = etEmployeeNumber.getText().toString().trim();
        if (BaseUtil.isEmpty(employeeNumber)){
            etEmployeeNumber.setError("请输入企业员工数");
            isCanLoad = false;
            return;
        }
        int iemployeeNumber = Integer.valueOf(employeeNumber);
        if (iemployeeNumber < 0 || iemployeeNumber > 999999) {
            etEmployeeNumber.setError("只能输入0~999999");
            isCanLoad = false;
            return;
        }

        partyMemberNumber = etPartyMemberNumber.getText().toString().trim();
        if (BaseUtil.isEmpty(partyMemberNumber)){
            etPartyMemberNumber.setError("请输入中共党员数量");
            isCanLoad = false;
            return;
        }
        int ipartyMemberNumber = Integer.valueOf(partyMemberNumber);
        if (iemployeeNumber < 0 || iemployeeNumber > 999999) {
            etPartyMemberNumber.setError("只能输入0~999999");
            isCanLoad = false;
            return;
        }
        if (ipartyMemberNumber > iemployeeNumber){
            etPartyMemberNumber.setError("不可大于企业员工数");
            isCanLoad = false;
            return;
        }


        theMemeberOfGuild = etTheMemeberOfGuild.getText().toString().trim();
        if (BaseUtil.isEmpty(theMemeberOfGuild)){
            etTheMemeberOfGuild.setError("请输入工会会员数量");
            isCanLoad = false;
            return;
        }
        int itheMemeberOfGuild = Integer.valueOf(theMemeberOfGuild);
        if (itheMemeberOfGuild < 0 || itheMemeberOfGuild > 999999) {
            etTheMemeberOfGuild.setError("只能输入0~999999");
            isCanLoad = false;
            return;
        }
        if (itheMemeberOfGuild > iemployeeNumber){
            etTheMemeberOfGuild.setError("不可大于企业员工数");
            isCanLoad = false;
            return;
        }

        theMemeberOfWomenFederation = etTheMemeberOfWomenFederation.getText().toString().trim();
        if (BaseUtil.isEmpty(theMemeberOfGuild)){
            etTheMemeberOfWomenFederation.setError("请输入妇女数量");
            isCanLoad = false;
            return;
        }
        int itheMemeberOfWomenFederation = Integer.valueOf(theMemeberOfWomenFederation);
        if (itheMemeberOfWomenFederation < 0 || itheMemeberOfWomenFederation > 999999) {
            etTheMemeberOfWomenFederation.setError("只能输入0~999999");
            isCanLoad = false;
            return;
        }
        if (itheMemeberOfWomenFederation > iemployeeNumber){
            etTheMemeberOfWomenFederation.setError("不可大于企业员工数");
            isCanLoad = false;
            return;
        }

        theMemeberOfGroup = etTheMemeberOfGroup.getText().toString().trim();
        if (BaseUtil.isEmpty(theMemeberOfGuild)){
            etTheMemeberOfGroup.setError("请输入共青团员数量");
            isCanLoad = false;
            return;
        }
        int itheMemeberOfGroup = Integer.valueOf(theMemeberOfGroup);
        if (itheMemeberOfGroup < 0 || itheMemeberOfGroup > 999999) {
            etTheMemeberOfGroup.setError("只能输入0~999999");
            isCanLoad = false;
            return;
        }
        if (itheMemeberOfGroup > iemployeeNumber){
            etTheMemeberOfGroup.setError("不可大于企业员工数");
            isCanLoad = false;
            return;
        }
        attentionExtentId = ((GlobalBean) spAttentionExtent.getSelectedItem()).getId();
        if (BaseUtil.isEmpty(attentionExtentId)) {
            ToastUtils.showToast(AddEconomicOrganizationActivity.this, "请选择关注程度");
            isCanLoad = false;
            return;
        }
        dangerTypeId = ((GlobalBean) spDangerType.getSelectedItem()).getId();
        if (BaseUtil.isEmpty(dangerTypeId)) {
            ToastUtils.showToast(AddEconomicOrganizationActivity.this, "请安全隐患类型");
            isCanLoad = false;
            return;
        }
    }

    @Override
    public void uploadSuccess(List<PhotoBean> beans) {
        commitData(beans.get(0).getPath());
    }

    private void commitData(String urlPath) {
        new AddEconomicOrganizationPest(this).addAddEconomicOrganization(this, orgId,
                residence, name, styleId, enterpriseMobile, enterpriseTelephone,
                isDangerousEnterprise, chiefCardTypeId, cardNo, chief, chiefSafe, telephone, mobileNumber,
                mobileNumberSafe, telephoneSafe, licenseNumber, isHaveOrganizationCondition, isHaveOrganization,
                isHaveGuild, isHaveGroup, isHaveWomenFederation, employeeNumber, partyMemberNumber,
                theMemeberOfGuild, theMemeberOfWomenFederation, theMemeberOfGroup, attentionExtentId,
                dangerTypeId, urlPath, 0, 0);
    }

    @Override
    public void commentSuccess(Boolean result) {
        LoadDialog.dismiss(AddEconomicOrganizationActivity.this);
        MyRxBus.get().post(new MsgEvent("EconomicOrganizationActivity", 1, "添加成功"));
        ToastUtils.showToast(AddEconomicOrganizationActivity.this, "添加成功");
        finish();
    }

    @Override
    public void showError(String message) {
        LoadDialog.dismiss(AddEconomicOrganizationActivity.this);
        ToastUtils.showToast(AddEconomicOrganizationActivity.this, message);
    }

    @Override
    public void getPublicList(PublicBean publicBean) {
        if ("新经济组织类别".equals(publicBean.getDomainName())) {
            style = publicBean.getDicts();
            if (style != null) {
                SpinnerPubAdapter adapter = new SpinnerPubAdapter(this, R.layout.item_text, style);
                spStyle.setAdapter(adapter);
            }
        }
        if ("证件代码".equals(publicBean.getDomainName())) {
            chiefCardType = publicBean.getDicts();
            if (chiefCardType != null) {
                SpinnerPubAdapter adapter = new SpinnerPubAdapter(this, R.layout.item_text, chiefCardType);
                spChiefCardType.setAdapter(adapter);
            }
        }
        if ("社会关注程度".equals(publicBean.getDomainName())) {
            attentionExtent = publicBean.getDicts();
            if (attentionExtent != null) {
                SpinnerPubAdapter adapter = new SpinnerPubAdapter(this, R.layout.item_text, attentionExtent);
                spAttentionExtent.setAdapter(adapter);
            }
        }
        if ("安全隐患类型".equals(publicBean.getDomainName())) {
            dangerType = publicBean.getDicts();
            if (dangerType != null) {
                SpinnerPubAdapter adapter = new SpinnerPubAdapter(this, R.layout.item_text, dangerType);
                spDangerType.setAdapter(adapter);
            }
        }
    }

}
